// utils/api.js
const app = getApp()
const baseUrl = app.globalData.apiUrl

// 封装请求方法
const request = (url, method, data) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: baseUrl + url,
      method: method || 'GET',
      data: data || {},
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token') || ''
      },
      success: (res) => {
        wx.hideLoading()

        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data.data)
          } else if (res.data.code === 401) {
            // 未登录或token过期
            wx.removeStorageSync('token')
            wx.showToast({
              title: res.data.msg || '请先登录',
              icon: 'none'
            })
            wx.navigateTo({
              url: '/pages/login/login'
            })
            reject(new Error(res.data.msg || '请先登录'))
          } else {
            wx.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            })
            reject(new Error(res.data.msg || '请求失败'))
          }
        } else {
          wx.showToast({
            title: '网络异常',
            icon: 'none'
          })
          reject(new Error('网络异常'))
        }
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 用户相关API
const userApi = {
  // 登录
  login: (data) => request('/user/login', 'POST', data),
  // 注册
  register: (data) => request('/user/register', 'POST', data),
  // 获取用户信息
  getUserInfo: () => request('/user/info', 'GET'),
  // 更新用户信息
  updateUserInfo: (data) => request('/user/update', 'POST', data)
}

// 单词本相关API
const wordBookApi = {
  // 获取推荐单词本
  getRecommendWordBooks: () => request('/wordbook/recommend', 'GET'),
  // 获取我的单词本
  getMyWordBooks: () => request('/wordbook/my', 'GET'),
  // 获取单词本详情
  getWordBookDetail: (id) => request(`/wordbook/detail/${id}`, 'GET'),
  // 创建单词本
  createWordBook: (data) => request('/wordbook/create', 'POST', data),
  // 更新单词本
  updateWordBook: (data) => request('/wordbook/update', 'POST', data),
  // 删除单词本
  deleteWordBook: (id) => request(`/wordbook/delete/${id}`, 'POST')
}

// 单词相关API
const wordApi = {
  // 获取单词列表
  getWords: (bookId, page = 1, pageSize = 10) => request(`/word/list?bookId=${bookId}&page=${page}&pageSize=${pageSize}`, 'GET'),
  // 获取单词详情
  getWordDetail: (id) => request(`/word/detail/${id}`, 'GET'),
  // 学习记录
  recordLearning: (data) => request('/word/learning/record', 'POST', data),
  // 获取学习记录
  getLearningRecords: (bookId) => request(`/word/learning/records?bookId=${bookId}`, 'GET')
}

// 测试相关API
const testApi = {
  // 生成测试
  generateTest: (bookId, count = 10) => request(`/test/generate?bookId=${bookId}&count=${count}`, 'GET'),
  // 提交测试
  submitTest: (data) => request('/test/submit', 'POST', data),
  // 获取测试历史
  getTestHistory: () => request('/test/history', 'GET')
}

// 统计相关API
const statsApi = {
  // 获取学习统计
  getLearningStats: () => request('/stats/learning', 'GET'),
  // 获取错误单词
  getErrorWords: () => request('/stats/errorWords', 'GET')
}

module.exports = {
  userApi,
  wordBookApi,
  wordApi,
  testApi,
  statsApi
}